#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文本转回答服务
基于星火大模型X1的简单文本转回答功能
"""

import json
import logging
from llm_service import LLMService

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class TextToResponseService:
    """文本转回答服务"""
    
    def __init__(self, config_path: str = "config.json"):
        """初始化服务"""
        with open(config_path, 'r', encoding='utf-8') as f:
            self.config = json.load(f)
        
        # 初始化LLM服务
        llm_config = self.config['llm']
        self.llm_service = LLMService(
            api_key=llm_config['api_key'],
            base_url=llm_config['base_url'],
            model=llm_config['model']
        )
        
        logger.info("文本转回答服务初始化完成")
    
    def get_response(self, text: str, stream: bool = False, 
                    enable_web_search: bool = False) -> str:
        """获取文本回答"""
        logger.info(f"处理文本: {text[:50]}...")
        
        try:
            response = self.llm_service.chat(
                user_message=text,
                stream=stream,
                enable_web_search=enable_web_search
            )
            
            logger.info(f"回答生成完成: {response[:50]}...")
            return response
            
        except Exception as e:
            logger.error(f"生成回答失败: {e}")
            return f"抱歉，生成回答时出现错误: {e}"
    
    def get_response_with_history(self, text: str, stream: bool = False,
                                 enable_web_search: bool = False) -> str:
        """获取带历史上下文的回答"""
        return self.get_response(text, stream, enable_web_search)
    
    def clear_history(self):
        """清空对话历史"""
        self.llm_service.clear_conversation_history()
        logger.info("对话历史已清空")
    
    def get_history(self):
        """获取对话历史"""
        return self.llm_service.get_conversation_history()


def main():
    """测试函数"""
    print("=== 文本转回答服务测试 ===")
    
    # 创建服务实例
    service = TextToResponseService()
    
    # 测试用例
    test_cases = [
        "你好，请介绍一下你自己",
        "请解释一下什么是人工智能",
        "推荐一本好书",
        "今天天气怎么样？"
    ]
    
    for i, test_text in enumerate(test_cases, 1):
        print(f"\n--- 测试 {i} ---")
        print(f"输入: {test_text}")
        print("回答: ", end="")
        
        try:
            response = service.get_response(test_text, stream=False)
            print(response)
        except Exception as e:
            print(f"错误: {e}")
    
    # 测试流式输出
    print(f"\n--- 流式输出测试 ---")
    test_text = "请用一句话总结Python编程语言的特点"
    print(f"输入: {test_text}")
    print("回答: ", end="")
    
    try:
        service.get_response(test_text, stream=True)
        print("\n")
    except Exception as e:
        print(f"错误: {e}")
    
    # 显示对话历史
    print(f"\n--- 对话历史 ---")
    history = service.get_history()
    for i, msg in enumerate(history):
        role = "用户" if msg["role"] == "user" else "助手"
        content = msg["content"][:100] + "..." if len(msg["content"]) > 100 else msg["content"]
        print(f"{i+1}. {role}: {content}")


if __name__ == "__main__":
    main()
